<template>
  <a-form class="padding-top" :model="categoryForm" ref="formRef" name="categoryForm">
    <a-form-item :label="index === 0 ?'分类名称':''"
                 :label-col="{span:6}"
                 :key="item.key"
                 :name="['category', index, 'name']"
                 :rules="{required:true,message:'请输入分类名称'}"
                 :wrapper-col="{span:16,offset:index=== 0 ? 0:6}"
                 v-for="(item,index) in categoryForm.category">
        <a-input :maxlength="8"
                 class="width"
                 v-model:value="item.name"
                 show-count/>
        <span class="hover margin-left" v-if="index>0" @click="removeFormItem(index)">
          <minus-circle-outlined/>
        </span>
    </a-form-item>
    <a-form-item :wrapper-col="{span:10,offset:6}">
      <a-button type="dashed" block @click="addFormItem"><plus-outlined/>添加更多</a-button>
    </a-form-item>
    <a-form-item :wrapper-col="{span:18,offset:6}">
      <a-space>
        <a-button type="primary" html-type="submit" @click="submitForm" :loading="loading">
          <check-outlined/>保存
        </a-button>
        <a-button @click="resetForm">重置</a-button>
      </a-space>
    </a-form-item>
  </a-form>
</template>
<script setup lang="ts">
import {CheckOutlined, MinusCircleOutlined, PlusOutlined} from "@ant-design/icons-vue";
import {reactive, ref} from "vue";
import type {FormInstance} from "ant-design-vue/es/form";
import useMessage from "@/plugin/useMessage";
import useStorage from "@/plugin/useStorage";
import {useCategoryStore} from "@/store/category";

const store = useCategoryStore()

const formRef = ref<FormInstance>()
let loading = ref<boolean>(false)

const categoryForm = reactive<{category:{key:number,name:string}[]}>({
  category:[{key:Date.now(),name:''}]
})

//添加分类操作
const addFormItem = ()=>{
  if(categoryForm.category.length < 10) {
    categoryForm.category.push({key:Date.now(),name:''})
  }else {
    return useMessage(403,'最多允许同时添加10条数据')
  }
}
//移除分类项
const removeFormItem = (index:number) => {
  categoryForm.category.splice(index,1)
}

//提交表单 并验证name不能为空
const submitForm = () => {
  formRef.value
      ?.validate()
      .then(async () => {
        //提交按钮进入loading状态
        loading.value = true
        setTimeout(() => {
          loading.value = false
        }, 2000)
        //删除掉key
        categoryForm.category.forEach((item)=>{
          delete item.key
        })
        //提交表单数据
        let res = await store.createItem(categoryForm.category)
        if (res.code === 200) {
          useStorage.removeItem('category')
        }
      })
      .catch(() => {});
};
const resetForm = () => {
  formRef.value?.resetFields();
};

</script>
<style scoped>

</style>